package Rule;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class LimitedDocument extends PlainDocument{
	
	private int maxLength=-1;
	private String allowCharAsString = null;// 允许的字符串格式（0123456789）
	/**
	 * 限制输入长度的构造函数
	 * @param maxLength,限制的长度值
	 */
	public LimitedDocument(int maxLength){
		super();
		this.maxLength=maxLength;
		
	}
	
	public void insertString(int offset,String str,AttributeSet attrSet) throws BadLocationException{
		if(str == null){
			return;
		}
		if (allowCharAsString != null && str.length() == 1) {
			if (allowCharAsString.indexOf(str) == -1) {
				return;// 不是所要求的字符格式，就直接返回，不进行下面的添加
			}
		}
		char[] charVal=str.toCharArray();
		String strOldValue=getText(0,getLength());
		char[] tmp=strOldValue.toCharArray();
		if(maxLength != -1 && (tmp.length + charVal.length > maxLength)) {
			//长度大于指定的长度maxLength，直接返回
			return;
		}
		super.insertString(offset, str, attrSet);
	}

}

